import {
  addUser,
  delUser,
  getRoles,
  GetRolesItem,
  GetUserItem,
  getUserList,
  GetUserListParams,
  putUser,
  putUserRoles,
  putUserStart,
} from "@/api";
import CustomBreadcrumb from "@/components/CustomBreadcrumb";
import { Card, Form, message } from "antd";
import { ChangeEvent, FC, useCallback, useEffect, useState } from "react";
import ModalAssign from "./components/ModalAssign";
import ModalEdit from "./components/ModalEdit";
import SearchAddBtn from "./components/searchAddBtn";
import UserTable from "./components/UserTable";
const Users: FC = () => {
  const [userList, setUserList] = useState<GetUserItem[]>([]);
  const [total, setTotal] = useState<number>(0);
  const [open, setOpen] = useState(false);
  const [pageSize, setPageSize] = useState<number>(2);
  const [form] = Form.useForm();
  const [query, setQuery] = useState<string>("");
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [title, setTitle] = useState("");
  const [editId, setEditId] = useState<number | null>(null);
  const [assignOpen, setAssignOpen] = useState(false);
  const [rolesList, setRolesList] = useState<GetRolesItem[]>([]);
  const [formRoles] = Form.useForm();
  const [assignId, setAssignId] = useState<number | null>(null);
  const [rid, setRid] = useState<number | null>(null);
  const getUserListData = useCallback(async (params: GetUserListParams) => {
    const res = await getUserList(params);
    setUserList(res.data.users);
    setTotal(res.data.total);
  }, []);
  const handlePageChange = useCallback(
    (page: number, pageSize: number) => {
      setCurrentPage(page);
      setPageSize(pageSize);
      getUserListData({
        pagenum: page,
        pagesize: pageSize,
      });
    },
    [getUserListData]
  );
  const handleDelete = useCallback(
    async (id: number) => {
      await delUser({ id });
      if (userList.length === 1 && currentPage > 1) {
        const newCurrentPage = currentPage - 1;
        setCurrentPage(newCurrentPage);
        getUserListData({
          pagenum: newCurrentPage,
          pagesize: pageSize,
        });
      } else {
        getUserListData({
          pagenum: currentPage,
          pagesize: pageSize,
        });
      }
      message.success("删除用户成功");
    },
    [currentPage, getUserListData, pageSize, userList.length]
  );
  const onEdit = useCallback(
    (id: number) => {
      setOpen(true);
      setTitle("编辑用户");
      setEditId(id);
      const user = userList.find((item) => item.id === id);
      form.setFieldsValue(user);
    },
    [form, userList]
  );
  const onChangeSwidth = useCallback(
    async (e: boolean, _mg_state: boolean, record: GetUserItem) => {
      try {
        const res = await putUserStart({ id: record.id, type: e });
        if (res.meta.status === 200) {
          await getUserListData({ pagenum: currentPage, pagesize: pageSize });
          message.success("修改用户状态成功");
        } else {
          message.error("修改用户状态失败");
        }
      } catch (error) {
        console.error("修改用户状态出错:", error);
        message.error("修改用户状态失败");
      }
    },
    [currentPage, getUserListData, pageSize]
  );

  const onAssign = useCallback(
    async (id: number) => {
      setAssignOpen(true);
      const res = await getRoles();
      setRolesList(res.data);
      const user = userList.find((item) => item.id === id);
      setAssignId(id);
      formRoles.setFieldsValue({
        username: user?.username,
        role_name: user?.role_name,
      });
    },
    [formRoles, userList]
  );
  const onAssignOk = async () => {
    if (assignId) {
      if (rid) {
        await putUserRoles(assignId, { rid: rid });
        setAssignOpen(false);
        message.success("分配角色成功");
        getUserListData({ pagenum: currentPage, pagesize: pageSize });
      }
    }
  };
  const queryChange = useCallback(
    (e: ChangeEvent<HTMLInputElement>) => {
      if (e.target.value.length > 0) {
        setQuery(e.target.value);
      } else {
        setQuery("");
        getUserListData({ pagenum: 1, pagesize: 2 });
      }
    },
    [getUserListData]
  );
  const resetQuery = useCallback(() => {
    setQuery("");
    getUserListData({ pagenum: 1, pagesize: 2 });
  }, [getUserListData]);

  const onOk = useCallback(async () => {
    try {
      if (editId) {
        const values = await form.validateFields();
        const newValues = {
          email: values.email,
          mobile: values.mobile,
        };
        await putUser({ ...newValues, id: editId });
        message.success("编辑用户成功");
      } else {
        const values = await form.validateFields();
        await addUser(values);
        message.success("添加用户成功");
      }
      setOpen(false);
      getUserListData({
        pagenum: currentPage,
        pagesize: pageSize,
      });
      form.resetFields();
    } catch (error) {
      console.log(error);
    }
  }, [editId, form, getUserListData, pageSize, currentPage]);

  useEffect(() => {
    getUserListData({ pagenum: 1, pagesize: 2 });
  }, [getUserListData]);
  return (
    <div>
      <CustomBreadcrumb items={[{ title: "用户列表" }]} />
      <Card>
        <div>
          {/* 搜索+添加+重置 */}
          <SearchAddBtn
            query={query}
            getUserListData={getUserListData}
            queryChange={queryChange}
            setTitle={setTitle}
            setOpen={setOpen}
            resetQuery={resetQuery}
          />
        </div>
        <UserTable
          pageSize={pageSize}
          total={total}
          handlePageChange={handlePageChange}
          dataSource={userList.map((item) => ({ ...item, key: item.id }))}
          onEdit={onEdit}
          handleDelete={handleDelete}
          onAssign={onAssign}
          onChangeSwidth={onChangeSwidth}
        />
      </Card>
      {/* 编辑用户 */}
      <ModalEdit
        setOpen={setOpen}
        title={title}
        open={open}
        onCancel={() => setOpen(false)}
        onOk={onOk}
        form={form}
      />
      {/* 分配角色 */}
      <ModalAssign
        setAssignOpen={setAssignOpen}
        assignOpen={assignOpen}
        onCancel={() => setAssignOpen(false)}
        onOk={onAssignOk}
        form={formRoles}
        rolesList={rolesList}
        setRid={setRid}
      />
    </div>
  );
};

export default Users;
